import 'dart:io';
import 'package:flutter/material.dart';

class ImageViewer extends StatefulWidget {
  /* File String */
  final List<dynamic> images;
  final int initialIndex;

  const ImageViewer({required this.images, required this.initialIndex});

  @override
  State<ImageViewer> createState() => _ImageViewerState();
}

class _ImageViewerState extends State<ImageViewer> {
  late PageController _controller;
  late int _currentIndex;

  @override
  void initState() {
    super.initState();
    _controller = PageController(initialPage: widget.initialIndex);
    _currentIndex = widget.initialIndex;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topRight,
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 指示器
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '${_currentIndex + 1} / ${widget.images.length}',
                style: const TextStyle(color: Colors.white),
              ),
            ),

            SizedBox(
              height: MediaQuery.of(context).size.height * 0.6,
              width: double.infinity,
              child: PageView.builder(
                controller: _controller,
                itemCount: widget.images.length,
                onPageChanged: (index) {
                  setState(() => _currentIndex = index);
                },
                itemBuilder: (_, index) {
                  if(widget.images[index] is File) {
                    return InteractiveViewer(
                      child: Image.file(
                          widget.images[index], fit: BoxFit.contain),
                    );
                  } else {
                    return InteractiveViewer(
                      child: Image.network(
                          widget.images[index], fit: BoxFit.contain),
                    );
                  }
                },
              ),
            ),
          ],
        ),

        // 关闭按钮
        IconButton(
          icon: const Icon(Icons.close, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ],
    );
  }
}